let seed = 0
let engine = marbleRaceEngineMatter0190
let uiEngine = marbleRaceUIEngine
let config = marbleRaceColor50
let levels = [
	marbleRaceLevelRotate
]
let currentLevel = levels.length

engine.seed(seed)

let n = config.colors.length
let m = config.teams.length

let breakNumber = [n / 2]
let breakCount = 0

let stat = new Array(n)
for (let i = 0; i < n; ++i)
	stat[i] = {
		status: marbleRaceConfig.constant.UNKNOWN,
		score: 0
	}
stat.totalRank = n

uiEngine.init(marbleRaceConfig.text.startGamePrompt, config, stat)

let levelCurrent = 0

let beforeGameStarted = true
document.addEventListener('keydown', function (event) {
	if (beforeGameStarted && event.code == marbleRaceConfig.startGameKeyCode) {
		beforeGameStarted = false

		function runLevel() {
			let isFinalLevel = false
			let currentMarbles = 0
			let gameLevel
			for (let i = 0; i < n; ++i)
				if (stat[i].status != marbleRaceConfig.constant.ELIMINATED)
					++currentMarbles;
			
			if (currentMarbles == 1) {
				isFinalLevel = true
				gameLevel = marbleRaceLevelC
			} else {
				while (breakNumber.length && currentMarbles <= breakNumber[breakNumber.length - 1]) {
					breakNumber.pop()
					++breakCount
				}
				
				if (breakCount) {
					--breakCount
					gameLevel = marbleRaceLevelR
				} else {
					if (currentLevel == levels.length)
						currentLevel = 0
					gameLevel = levels[currentLevel++]
				}
			}
			let isLevel = marbleRaceConfig.isLevel[gameLevel.type]
			let levelText = ''
			if (isLevel)
				levelText = marbleRaceConfig.text.level.replace('%l', (++levelCurrent).toString())
			else
				levelText = gameLevel.title
			uiEngine.init(levelText, config, stat, { calcTime: true })

			let onEnd
			if (isFinalLevel)
				onEnd = function () { }
			else
				onEnd = function () {
					setTimeout(function () {
						uiEngine.del();
						engine.del();
						runLevel()
					}, marbleRaceConfig.nextLevelDelay)
				}

			engine.start(gameLevel, config, stat, onEnd)
		}
		uiEngine.del()
		runLevel()
	}
})